using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/**武器管理类 */
public class WeaponMgr : MonoBehaviour
{
    /**武器容器 */
    public GameObject weaponPanel;

    /**武器预制体 */
    public GameObject weaponPrefab;
    
    /**当前拥有的武器类型 */ 
    private List<GameWeapon> _hasWeaponTypes = new List<GameWeapon>();

    /**当前选择的武器类型 */
    private GameWeapon _curWeaponType = GameWeapon.Null;
    
    /**武器集合 */
    public List<GameObject> weapons = new List<GameObject>();
    
    public static WeaponMgr instance;

    private void Awake()
    {
        instance = this;
    }

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.K))
        {
             nextWeapon();
        }
    }

    /**清空数据 */
    public void ClearData()
    {
        _hasWeaponTypes.Clear();
        
        weapons.ForEach(Destroy);
        weapons.Clear();
        
        SetWeaponType(GameWeapon.Null);
    }
    
    /**添加武器 */
    public void AddWeapon(GameWeapon type)
    {
        if (_hasWeaponTypes.IndexOf(type) != -1)
        {
            // 已有该武器
            return;
        }
        _hasWeaponTypes.Add(type);
        
        // 创建武器
        var weapon = Instantiate(weaponPrefab, weaponPanel.transform);
        weapon.GetComponent<WeaponUI>().SetType(type);
        weapon.GetComponent<WeaponUI>().onSelectWeapon.AddListener(SetWeaponType);
        weapon.transform.SetSiblingIndex(0);

        // 添加到集合
        weapons.Add(weapon);
        
        SetWeaponType(type);
    }

    /**设置当前武器类型 */
    private void SetWeaponType(GameWeapon weapon)
    {
        _curWeaponType = weapon;
        UpdateWeapons();
    }

    /**切换下一个武器 */
    private void nextWeapon()
    {
        if (_hasWeaponTypes.Count < 1)
        {
            // 没有武器
            return;
        }

        var index = _hasWeaponTypes.IndexOf(_curWeaponType);
        SetWeaponType(_hasWeaponTypes[(index + 1) % _hasWeaponTypes.Count]);
    }

    /**获取当前武器类型 */
    public GameWeapon GetWeaponType()
    {
        return _curWeaponType;
    }
    
    /**刷新拥有武器集合 */
    private void UpdateWeapons()
    {
        weapons.ForEach(weapon =>
        {
            weapon.GetComponent<WeaponUI>().IsSelect(_curWeaponType);
        });
    }
}
